package com.helloae.chap05;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;

import com.esri.arcgis.carto.FeatureLayer;
import com.esri.arcgis.datasourcesfile.ShapefileWorkspaceFactory;
import com.esri.arcgis.geodatabase.IFeatureClass;
import com.esri.arcgis.geodatabase.IFeatureWorkspace;
import com.esri.arcgis.geodatabase.IObjectClass;
import com.esri.arcgis.geodatabase.IObjectClassProxy;
import com.esri.arcgis.geodatabase.IRelationshipClass;
import com.esri.arcgis.geodatabase.ITable;
import com.esri.arcgis.geodatabase.MemoryRelationshipClassFactory;
import com.esri.arcgis.geodatabase.esriJoinType;
import com.esri.arcgis.geodatabase.esriRelCardinality;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;

/**
 * 将wpdata.dbf关联(join)到wp.shp中。<br>
 * 示例章节：5.6.1
 * @author light
 *
 */
public class JoinTableToLayer {

	public static void main(String[] args) throws UnknownHostException, IOException {
		// 初始化AE许可
		EngineInitializer.initializeEngine();
		AoInitialize ao = new AoInitialize();
		ao.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
		
		//使用ShapefileWorkspaceFactory.openFromFile的方法创建一个Workspace
		ShapefileWorkspaceFactory pWF = new ShapefileWorkspaceFactory();
		String ecliseWorkspace = System.getenv("Eclipse3.6Workspace");
		IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace) pWF
				.openFromFile(ecliseWorkspace + "HelloAE" + File.separator
						+ "DataSet" + File.separator + "chap05", 0);
		//加载图层wp.shp
		IFeatureClass pFeatureClass = pFeatureWorkspace
				.openFeatureClass("wp");
		
		//打开用于join的数据集wpdata，即表wpdata.dbf
		ITable pFromTable = pFeatureWorkspace.openTable("wpdata");
		
		//指定要join的表、图层及字段
		MemoryRelationshipClassFactory pMemRelFact = new MemoryRelationshipClassFactory();
		//将ITable转型成IObjectClass，否则程序不认该参数
		IObjectClass originForeignClass =new IObjectClassProxy(pFromTable);
		//这里的倒数第2、3个参数完全没有弄懂什么意思，写什么都不影响程序。有机会再研究。
		IRelationshipClass pRelClass = pMemRelFact.open("TableToLayer", pFeatureClass, "ID", originForeignClass, "ID", "hello", "hello2", esriRelCardinality.esriRelCardinalityOneToOne);
		
		//创建一个FeatureLayer用于存储join
		FeatureLayer pFeatureLayer = new FeatureLayer();
		pFeatureLayer.setFeatureClassByRef(pFeatureClass);
		System.out.println("join以前的字段数量为："+pFeatureLayer.getFieldCount());
		
		//执行join
		pFeatureLayer.displayRelationshipClass(pRelClass, esriJoinType.esriLeftInnerJoin);
		System.out.println("join以后的字段数量为："+pFeatureLayer.getFieldCount());
		
		ao.shutdown();
		System.out.println("Congratulations!");
	}

}
